#JSON EVENTS
from time import time
from json import json_encode
from django.utils.simplejson import loads as json_decode
from django.http import HttpResponse
from django.shortcuts import render_to_response

def json_response(data):
    return HttpResponse(json_encode(data))

class EventsBridge(object):
    EVENT_QUEUE = {}
    HANDLERS = {}
    
    @classmethod
    def client_trigger(cls, request, event_kind, event_data):
        event = {'event_kind':event_kind, 'event_data':event_data,}
        cls.EVENT_QUEUE.setdefault(request.session.session_key, []).append(event)
    
    @classmethod
    def get_client_events(cls, request):
        key = request.session.session_key
        while True:
            q = cls.EVENT_QUEUE.get(key, [])
            if q:
                del cls.EVENT_QUEUE[key]
                break
        
        return json_response(q)
    
    @classmethod
    def server_bind(cls, event_kind, callback):
        cls.HANDLERS.setdefault(event_kind, []).append(callback)
    
    @classmethod
    def trigger_server_event(cls, request):
        event_kind = request.POST.get('event_kind')
        event_data = request.POST.get('event_data')
        if not cls.HANDLERS.get(event_kind):
            return json_response({'status':'500'})
        
        request.event_kind = event_kind
        request.event_data = json_decode(event_data) if event_data else '[]' 
        
        for x in cls.HANDLERS[event_kind]: x(request)
        return json_response({'status': '200'})

def greet(request):
    print request.event_data
    EventsBridge.client_trigger(request, 'GREET_BACK', {'message':'hi there', 'echo':request.event_data})
EventsBridge.server_bind('SEND_GREETING', greet)

from threading import Thread
import random
import time

class Zombies(Thread):
    def __init__(self, request):
        self.request = request
        super(Zombies, self).__init__()
    
    def run(self):
        while True:
            EventsBridge.client_trigger(self.request, 'SHOW_ZOMBIE', {
                'x': random.randint(1,1000),
                'y': random.randint(1,600),})
            time.sleep(random.randint(1,3))

def zombie_killed(request):
    request.session['score'] += 1
    request.session.save()
    EventsBridge.client_trigger(request, 'UPDATE_SCORE', request.session['score'])
EventsBridge.server_bind('ZOMBIE_KILLED', zombie_killed)

def game(request):
    request.session['score'] = 0
    Zombies(request).start()
    return render_to_response('index.html')
